﻿using System.Collections.Generic;
using ZhCun.DbCore.Cores;
using ZhCun.DbCore.Entitys;
using ZhCun.Utils;
using ZhCun.WebUtils.VModel;

namespace ZhCun.WebUtils.DB
{
    /// <summary>
    /// 分页查询基类
    /// </summary>
    /// <typeparam name="TListArg">查询参数类型</typeparam>
    /// <typeparam name="TListModel">查询结果类型</typeparam>
    public abstract class BLLReadPager<TListArg, TListModel> : BLLBase
        where TListArg : ArgGetList, new()
        where TListModel : EntityBase, new()
    {
        protected abstract void SetQueryOption(TListArg arg, QueryCondition<TListModel> query);

        public virtual ApiResultList<TListModel> GetList(TListArg arg)
        {
            var rList =
            GetPagerList<TListModel>(arg.page, arg.limit, out int total, query =>
            {
                SetQueryOption(arg, query);
            });
            return this.RetOK(rList, total);
        }
    }

    /// <summary>
    /// 增删查改基类 1
    /// </summary>
    /// <typeparam name="TListArg">查询参数</typeparam>
    /// <typeparam name="TSaveModel">保存实体类型</typeparam>
    /// <typeparam name="TListModel">查询结果类型</typeparam>
    public abstract class BLLCrudBase<TListArg, TSaveModel, TListModel> : BLLReadPager<TListArg, TListModel>
        where TListArg : ArgGetList, new()
        where TSaveModel : EntityBase, new()
        where TListModel : EntityBase, new()
    {
        protected abstract bool CheckSaveArg(TSaveModel model, bool isAdd, out string msg);

        protected abstract ExecResult GetDelResult(string id);

        public virtual ApiResult Add(TSaveModel model)
        {
            if (!CheckSaveArg(model, true, out string msg))
            {
                return this.RetErr(msg);
            }
            var r = DB.Insert(model);
            if (r.RowCount == 1)
            {
                return this.RetOK("保存成功");
            }
            else
            {
                return this.RetErr("保存失败");
            }
        }

        public virtual ApiResult Update(TSaveModel model)
        {
            if (!CheckSaveArg(model, false, out string msg))
            {
                return this.RetErr(msg);
            }
            var r = DB.Update(model);
            if (r.RowCount == 1)
            {
                return this.RetOK("更新成功");
            }
            else
            {
                return this.RetErr("更新失败");
            }
        }

        public virtual ApiResult Del(string id)
        {
            var r = GetDelResult(id);
            if (r.RowCount == 1)
            {
                return this.RetOK("删除成功");
            }
            else
            {
                return this.RetErr("删除失败");
            }
        }
    }

    /// <summary>
    /// 增删查改基类 重载
    /// </summary>
    public abstract class BLLCrudBase<TListArg, TSaveModel> : BLLCrudBase<TListArg, TSaveModel, TSaveModel>
        where TListArg : ArgGetList, new()
        where TSaveModel : EntityBase, new()
    { }
}